<template>
  <div>
    <el-dialog v-model="dialogSelectVisible" draggable title="查看规则" width="60%" :before-close="handleClose">
			<!-- <el-button type="primary" @click="handleAdd" style="margin-bottom: 10px;">新增</el-button> -->
			<el-table :data="tableData" style="width: 100%" border>
				<el-table-column label="场景名称" prop="sceneName" show-overflow-tooltip />
				<el-table-column label="场景描述" prop="description" show-overflow-tooltip />
				<el-table-column label="触发方式" show-overflow-tooltip width="90">
					<template #default="scope">
						<div style="" v-if="scope.row.type == 0">设备</div>
						<div style="" v-if="scope.row.type == 1">定时</div>
					</template>
				</el-table-column>
				<el-table-column label="业务类型" width="90px">
					<template #default="scope">
						<div v-if="scope.row.actionType == 0">联动</div>
						<div v-if="scope.row.actionType == 1">告警</div>
					</template>
				</el-table-column>
				<el-table-column label="创建时间" prop="createTime" show-overflow-tooltip width="160" />
				<el-table-column label="运行状态" width="90px">
					<template #default="scope">
						<div v-if="scope.row.status == 1">
							<el-tag type="success">运行中</el-tag>
						</div>
						<div v-if="scope.row.status == 2"><el-tag type="danger">未启动</el-tag></div>
					</template>
				</el-table-column>
				<el-table-column label="" width="140">
					<template #default="scope">
						<el-button icon="VideoPlay" @click="handleStartUp(scope.row)" text type="primary" v-if="scope.row.status == 2">
							启动
						</el-button>
						<!-- 停止 -->
						<el-button icon="VideoPause" @click="handleStartUp(scope.row)" text type="primary" v-if="scope.row.status == 1">
							停止
						</el-button>
						<!-- 触发 -->
						<el-button
							icon="RefreshRight"
							@click="beforeValidatePassword(scope.row.linkageId)"
							text
							type="primary"
							:disabled="scope.row.status == 1 ? false : true"
						>
							触发
						</el-button>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="290">
					<template #default="scope">
						<!-- <el-button icon="Edit" type="primary" text @click="handleEdit(scope.row)" :disabled="scope.row.status == 2 ? false : true">编辑</el-button> -->
						<!-- <el-button icon="Edit" type="primary" text @click="formDialogRef.openDialog(scope.row.linkageId,editParentId)" :disabled="scope.row.status == 2 ? false : true">编辑</el-button> -->
						<el-button icon="View" @click="formDialogDetailsRef.openDialog(scope.row.linkageId)" text type="primary"
							>{{ $t('common.viewBtn') }}
						</el-button>
						<!-- 日志 -->
						<el-button icon="Document" @click="permessionRef.openDialog(scope.row.linkageId)" text type="primary">
							日志
						</el-button>
						<!-- 删除 -->
						<el-button icon="delete" @click="handleRuleDelete(scope.row)" text type="primary" v-auth="'exsecs_sceneLinkage_del'">
							移除绑定
						</el-button>
					</template>
				</el-table-column>
			</el-table>
			<!-- <template #footer>
				<div class="dialog-footer">
					<el-button @click="dialogSelectVisible = false">取消</el-button>
					<el-button type="primary" @click="handleCheckSelectRule"> 关闭 </el-button>
				</div>
			</template> -->
		</el-dialog>
   
    
    <!-- 详情 -->
		<Details-page @refresh="getDataList()" ref="formDialogDetailsRef" />
    <form-dialog-log @refresh="getDataList()" ref="permessionRef" />
    <el-dialog title="警告" v-model="showWarn" width="30%">
			<el-input v-model="password" type="password" placeholder="请输入密码校验" clearable style="margin-bottom: 20px"> </el-input>
			<span slot="footer" class="dialog-footer">
				<el-button @click="showWarn = false">取 消</el-button>
				<el-button type="primary" @click="validatePassword">确 定</el-button>
			</span>
		</el-dialog>
  </div>
</template>

<script lang="ts" setup name="ruleDialog">
  import { queryCheckList, getListData, pageList, delRuleObj} from '/@/api/basiciot/iconfiguration/list';
  import { BasicTableProps, useTable } from '/@/hooks/table';
  import { useMessage, useMessageBox } from '/@/hooks/message';
  import { updateStatus, getTrigger } from '/@/api/scene/sceneLinkage';
  import { useI18n } from 'vue-i18n';
  import { checkPassword } from '/@/api/admin/user';

  const { t } = useI18n();

  const DetailsPage = defineAsyncComponent(() => import('/@/views/basiciot/ruleengine/scenelinkage/details.vue'));
  const FormDialogLog = defineAsyncComponent(() => import('/@/views/basiciot/ruleengine/scenelinkage/formLog.vue'));

  // 定义表格查询、后台调用的API
  const state: BasicTableProps = reactive<BasicTableProps>({
    queryForm: {
      scadaName: '',
      bindFlag: '',
    },
    pageList: pageList,
  });

  const { getDataList, currentChangeHandle, sizeChangeHandle, downBlobFile, tableStyle } = useTable(state);
  const permessionRef = ref();
  const formDialogDetailsRef = ref(); // 详情
  const dialogSelectVisible = ref(false);
  const dialogVisible = ref(false);
  const tableData: any = ref([]);
  let objDataId: any = ref({});
  const showWarn = ref(false);
  const triggerId = ref('');
  const password = ref('');

  const show = (id:string) => {
    tableData.value = [];
    objDataId.value = id
    dialogSelectVisible.value = true;
    getListData({ current: 1, size: 999, parentId: id }).then((res1) => {
      queryCheckList({ current: 1, size: 999 }).then((res) => {
        let combinedArray:any = [];
        res1.data.records.forEach((item1:any) => {
          let aa:any = {};
          res.data.records.forEach((item2:any) => {
            if (item1.linkedId === item2.linkageId) {
              aa.detailsId = item1.id;
              aa.createBy = item1.createBy;
              aa.createTime = item1.createTime;
              aa.linkedId = item1.linkedId;
              aa.updateBy = item1.updateBy;
              aa.updateTime = item1.updateTime;
              let combinedItem = Object.assign({}, aa, item2);
              combinedArray.push(combinedItem);
            }
          });
        });
        tableData.value = combinedArray;
      });
    });
  }
// 启动 / 启动
const handleStartUp = async (val) => {
	try {
		await useMessageBox().confirm(t('确认要执行该操作吗？'));
	} catch {
		return;
	}
	try {
		await updateStatus({
			linkageId: val.linkageId,
			status: val.status == 2 ? '1' : '2',
		});
		loadData();
		useMessage().success(t('操作成功'));
	} catch (err: any) {
		useMessage().error(err.msg);
	}
};
// 用于规则弹窗中操作后 刷新规则页面
const loadData = async () => {
	getListData({ current: 1, size: 999, parentId: objDataId.value }).then((res1) => {
		queryCheckList({ current: 1, size: 999 }).then((res) => {
			let combinedArray = [];
			res1.data.records.forEach((item1) => {
				var aa = {};
				res.data.records.forEach((item2) => {
					if (item1.linkedId === item2.linkageId) {
						aa.detailsId = item1.id;
						aa.createBy = item1.createBy;
						aa.createTime = item1.createTime;
						aa.linkedId = item1.linkedId;
						aa.updateBy = item1.updateBy;
						aa.updateTime = item1.updateTime;
						let combinedItem = Object.assign({}, aa, item2);
						combinedArray.push(combinedItem);
					}
				});
			});
			tableData.value = combinedArray;
		});
	});
};

// 删除操作
const handleRuleDelete = async (val: string) => {
	try {
		await useMessageBox().confirm(t('此操作将移除绑定'));
	} catch {
		return;
	}
	try {
		await delRuleObj(val.detailsId);
		loadData();
		useMessage().success(t('common.delSuccessText'));
	} catch (err: any) {
		useMessage().error(err.msg);
	}
};

const beforeValidatePassword = (val) => {
	showWarn.value = true;
	triggerId.value = val;
};

// 触发
const handleTrigger = async (val) => {
	try {
		await getTrigger(val);
		loadData();
		useMessage().success(t('触发成功'));
	} catch (err: any) {
		useMessage().error(err.msg);
	}
};
//验证密码
const validatePassword = async () => {
	if (!password.value) {
		password.value = '';
		useMessage().error('校验密码错误请重试');
		return false;
	}
	try {
		await checkPassword(password.value).then((res) => {
			showWarn.value = false;
			handleTrigger(triggerId.value);
		});
	} catch (e) {
		console.log(e);
		useMessage().error('校验密码错误请重试');
	} finally {
		password.value = '';
	}
};

// 暴露变量 只有暴漏出来的变量 父组件才能使用
defineExpose({
  show
});
</script>

<style>

</style>